﻿using NPOI.HSSF.UserModel;
using OMG.Fill.Frunit.Model.Ent;
using OMG.Fill.Frunit.Services;
using ProjectShare;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Web;
using System.Web.Http;
namespace OMG.Fill.Frunit.Model.UI.Controllers
{
    public class FruExportController : ApiController
    {
        FruExportServices fruExportServices = new FruExportServices();
        
        //[ApiActionAuthorize("获取表4外销调查表T_FruExport分页列表对象操作")]
        //[ApiActionException]
        public Pager<List<FruExportEntity>> PostPageList(FruExportQuery query)
        {
            return fruExportServices.GetPageList(query);
        }
        //[ApiActionAuthorize("新增表4外销调查表T_FruExport指定对象操作")]
        //[ApiActionException]
        public ResResult<int> Post(FruExportEntity model) {
            return fruExportServices.AddInfo(model);
        }
        //[ApiActionAuthorize("修改表4外销调查表T_FruExport指定对象操作")]
        //[ApiActionException]
        public ResResult<int> Put(FruExportEntity model)
        {
            return fruExportServices.UpdateInfo(model);
        }
        //[ApiActionAuthorize("删除表4外销调查表T_FruExport指定对象操作")]
        //[ApiActionException]
        public ResResult<int> Delete(string id)
        {
            return fruExportServices.DeleteInfo(id);
        }
        //[ApiActionAuthorize("获取表4外销调查表T_FruExport指定对象操作")]
        //[ApiActionException]
        public ResResult<FruExportEntity> Get(string id)
        {
            return fruExportServices.GetModel(id);
        }
        /// <summary>
        /// 导出数据
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public MemoryStream Method(VegNowModel model)
        {
            FileStream file = null;
            //创建下载Excel文件
            var workbook = new HSSFWorkbook();
            string fileIndex = HttpRuntime.AppDomainAppPath.ToString();
            string filename = @"tempfile\Basic" + DateTime.Now.Ticks.ToString() + ".xls";//临时文件，定期在tempfile手动删除
            string tempExcel = fileIndex + filename;//临时文件路径及全称
            string templateName = fileIndex + @"Excel\FruDownload.xls";//模板文件
            file = new FileStream(templateName, FileMode.Open, FileAccess.Read);//读模板文件
            HSSFWorkbook templateBook = new HSSFWorkbook(file);//读取模板文件信息转换成Excel工作薄
            HSSFSheet sheet = templateBook.GetSheet("FruExport") as HSSFSheet;//读取模板所在sheet位置
            ResResult<FruExportViewModel> pagelist = fruExportServices.GetModel(model);//数据获取

            HSSFRow row = (HSSFRow)sheet.GetRow(5);//读取模板第4行
            var style = row.GetCell(1).CellStyle;//读取模板第4行第2单元格样式并保存
            row.GetCell(1).CellStyle = style;//对第4行第2单元格设置原来样式

            HSSFRow datarow = (HSSFRow)sheet.CreateRow(5);
            //var pecSaleNumber = "";
            //var pecSaleMoney = "";
            //if (pagelist.model.OldSaleNumber != null&& pagelist.model.SaleNumber != null)
            //{
            //    pecSaleNumber = (pagelist.model.SaleNumber * 1) - (pagelist.model.OldSaleNumber * 1) / (pagelist.model.OldSaleNumber * 1) + "";
            //}
            //if (pagelist.model.OldSaleMoney != null && pagelist.model.SaleMoney != null)
            //{
            //    pecSaleMoney = (pagelist.model.SaleMoney * 1) - (pagelist.model.OldSaleMoney * 1) / (pagelist.model.OldSaleMoney * 1) + "";
            //}
            datarow.CreateCell(0).SetCellValue(pagelist.model.ProductNumber == null ? "" : string.Format("{0:N2}",pagelist.model.ProductNumber));
            datarow.CreateCell(1).SetCellValue(pagelist.model.SaleNumber == null ? "" : string.Format("{0:N2}", pagelist.model.SaleNumber));
            datarow.CreateCell(2).SetCellValue(pagelist.model.pecSaleNumber == null ? "" : string.Format("{0:N2}", pagelist.model.pecSaleNumber));
            datarow.CreateCell(3).SetCellValue(pagelist.model.ProductMoney == null ? "" : string.Format("{0:N2}", pagelist.model.ProductMoney));
            datarow.CreateCell(4).SetCellValue(pagelist.model.SaleMoney == null ? "" : string.Format("{0:N2}", pagelist.model.SaleMoney));
            datarow.CreateCell(5).SetCellValue(pagelist.model.pecSaleMoney == null ? "" : string.Format("{0:N2}", pagelist.model.pecSaleMoney));
            datarow.GetCell(0).CellStyle = style;
            datarow.GetCell(1).CellStyle = style;
            datarow.GetCell(2).CellStyle = style;
            datarow.GetCell(3).CellStyle = style;
            datarow.GetCell(4).CellStyle = style;
            datarow.GetCell(5).CellStyle = style;
            sheet.CopyTo(workbook, "Sheet1", true, true);
            using (MemoryStream ms = new MemoryStream())
            {
                workbook.Write(ms);
                ms.Flush();
                ms.Position = 0;
                return ms;
            }
        }
        /// <summary>
        /// 导出下载响应
        /// </summary>
        /// <param name="ReportCode"></param>
        public void GetExcelData(string ReportCode, string FillInYear, string AreaCode)
        {
            AreaServices areaServices = new AreaServices();
            string AreaName = areaServices.GetByCodeModel(AreaCode).model.Name;
            VegNowModel model = new VegNowModel();
            model.AreaCode = AreaCode;
            model.FillInYear = FillInYear;
            model.ReportCode = ReportCode;
            //打开完成excel文件并下载
            HttpContext curContext = HttpContext.Current;
            // 设置编码和附件格式
            curContext.Response.AddHeader("Access-Control-Allow-Origin", "*");
            curContext.Response.ContentType = "application/vnd.ms-excel";
            curContext.Response.ContentEncoding = Encoding.UTF8;
            curContext.Response.Charset = "";
            //curContext.Response.Charset = "GB2312";//防止中文出现乱码
            //System.Globalization.CultureInfo myCItrad = new System.Globalization.CultureInfo("ZH-CN", true);//防止中文出现乱码
            // curContext.Response.ContentEncoding = Encoding.GetEncoding("GB2312");  //设置输出流为简体中文          
            string strFileName = "（三）"+model.FillInYear+"-"+ AreaName + "-水果外销统计表.xls";
            curContext.Response.AppendHeader("Content-Disposition",
                "attachment;filename=" + HttpUtility.UrlEncode(strFileName, Encoding.UTF8));
            //curContext.Response.AppendHeader("Content-Disposition",
             //   "attachment;filename=" + strFileName);
            curContext.Response.BinaryWrite(Method(model).GetBuffer());
            curContext.Response.End();
        }

        /// <summary>
        /// 导入数据
        /// </summary>
        /// <param name="ReportCode"></param>
        /// <param name="AreaCode"></param>
        /// <param name="FillInYear"></param>
        /// <returns></returns>
        public List<ResResult<int>> PostImportData(string ReportCode, string AreaCode, string FillInYear)
        {
            List<ResResult<int>> obj = new List<ResResult<int>>();
            ResResult<int> SingleObj = new ResResult<int>();
            HttpContext curContext = HttpContext.Current;
            HttpFileCollection files = curContext.Request.Files;
            ReportServices reportServices = new ReportServices();
            if (curContext.Request.Files.Count != 0)
            {
                HttpPostedFile upfile = files[0];
                if (upfile != null && upfile.ContentLength > 0)
                {
                    string temppath = curContext.Server.MapPath("~/App_Data/temppath");
                    if (!Directory.Exists(temppath))//判断文件夹是否存在 
                    {
                        Directory.CreateDirectory(temppath);//不存在则创建文件夹 
                    }
                    string filetype = Path.GetExtension(upfile.FileName);
                    string filenewName = Guid.NewGuid().ToString().Replace("-", "") + filetype;
                    string strpath = Path.Combine(temppath, filenewName);
                    upfile.SaveAs(strpath);

                    var ExpList = fruExportServices.ExcelToModel(strpath, filetype, "", 5);
                    foreach (var item in ExpList)
                    {
                        if (item.pecSaleMoney != null || item.pecSaleNumber != null || item.ProductMoney != null || item.ProductNumber != null ||
                            item.SaleMoney != null || item.SaleNumber != null)
                        {


                            string year = FillInYear.Substring(0, 4);
                            if (fruExportServices.CheckRepCreate(ReportCode, AreaCode, year))
                            {
                                SingleObj.status = -1;
                                SingleObj.message = year + "的报表没有填报数据！！";
                                obj.Add(SingleObj);
                            }
                            else
                            {
                                string ReportId = fruExportServices.GetReportId(ReportCode, AreaCode, year);
                                item.ReportId = ReportId;
                                //判断list中是否初始化过报表
                                if (fruExportServices.CheckRepCount(ReportId))
                                {
                                    //没初始化过进来
                                    SingleObj = fruExportServices.AddInfo(item);
                                }
                                else
                                {
                                    SingleObj = fruExportServices.UpdateInfo(item);
                                }
                                SingleObj.status = DefaultKey.SuccessResult; ;
                                SingleObj.message = item.year + "数据导入成功！！";
                                reportServices.UpStatus(ReportId, "2", "");
                                obj.Add(SingleObj);
                            }
                        }
                    }
                    Directory.Delete(temppath, true);
                }


            }
            return obj;
        }

        /// <summary>
        /// 获取外销统计列表数据
        /// </summary>
        /// <param name="AreaCode"></param>
        /// <param name="FillInYear"></param>
        /// <returns></returns>
     public ResResult<FruStatisModel> GetStatisListData(string AreaCode,string FillInYear)
        {
            return fruExportServices.getStatisListData(AreaCode,FillInYear);
        }


     public void GetStatisExcel(string AreaCode, string FillInYear)
        {
            AreaServices areaServices = new AreaServices();
            string AreaName = areaServices.GetByCodeModel(AreaCode).model.Name;            
            //打开完成excel文件并下载
            HttpContext curContext = HttpContext.Current;
            // 设置编码和附件格式
            curContext.Response.AddHeader("Access-Control-Allow-Origin", "*");
            curContext.Response.ContentType = "application/vnd.ms-excel";
            curContext.Response.ContentEncoding = Encoding.UTF8;
            curContext.Response.Charset = "";                
            string strFileName =  FillInYear + "年-" + AreaName + "-水果外销统计汇总表.xls";
            curContext.Response.AppendHeader("Content-Disposition",
                "attachment;filename=" + HttpUtility.UrlEncode(strFileName, Encoding.UTF8));
            //curContext.Response.AppendHeader("Content-Disposition",
            //   "attachment;filename=" + strFileName);
            curContext.Response.BinaryWrite(fruExportServices.loadStatis(AreaCode,FillInYear).GetBuffer());
            curContext.Response.End();
        }

        //public MemoryStream loadStatis(string AreaCode, string FillInYear)
        //{
        //    FileStream file = null;
        //    //创建下载Excel文件
        //    var workbook = new HSSFWorkbook();
        //    string fileIndex = HttpRuntime.AppDomainAppPath.ToString();
        //    string filename = @"tempfile\Basic" + DateTime.Now.Ticks.ToString() + ".xls";//临时文件，定期在tempfile手动删除
        //    string tempExcel = fileIndex + filename;//临时文件路径及全称
        //    string templateName = fileIndex + @"Excel\FruStatisDownload.xls";//模板文件
        //    file = new FileStream(templateName, FileMode.Open, FileAccess.Read);//读模板文件
        //    HSSFWorkbook templateBook = new HSSFWorkbook(file);//读取模板文件信息转换成Excel工作薄
        //    HSSFSheet sheet = templateBook.GetSheet("FruExport") as HSSFSheet;//读取模板所在sheet位置
        //    List<FruExportStatisModel> pagelist = (List < FruExportStatisModel > )fruExportServices.getStatisListData(AreaCode, FillInYear).model.list;//数据获取

        //    HSSFRow row = (HSSFRow)sheet.GetRow(2);//读取模板第3行
        //    var style = row.GetCell(1).CellStyle;//读取模板第3行第2单元格样式并保存
        //    row.GetCell(1).CellStyle = style;//对第3行第2单元格设置原来样式

            
        //    if (pagelist.Count > 0)
        //    {
        //        for(int i = 0; i < pagelist.Count; i++)
        //        {
        //            HSSFRow datarow = (HSSFRow)sheet.CreateRow(2+i);
        //            datarow.CreateCell(0).SetCellValue(pagelist[i].AreaName == null ? "" : pagelist[i].AreaName);
        //            datarow.CreateCell(1).SetCellValue(pagelist[i].ProductNumber == null ? "" : pagelist[i].ProductNumber.ToString());
        //            datarow.CreateCell(2).SetCellValue(pagelist[i].SaleNumber == null ? "" : pagelist[i].SaleNumber.ToString());                    
        //            datarow.CreateCell(3).SetCellValue(pagelist[i].ProductMoney == null ? "" : pagelist[i].ProductMoney.ToString());
        //            datarow.CreateCell(4).SetCellValue(pagelist[i].SaleMoney == null ? "" : pagelist[i].SaleMoney.ToString());                    
        //            datarow.GetCell(0).CellStyle = style;
        //            datarow.GetCell(1).CellStyle = style;
        //            datarow.GetCell(2).CellStyle = style;
        //            datarow.GetCell(3).CellStyle = style;
        //            datarow.GetCell(4).CellStyle = style;                    
        //        }
        //    }
            
        //    sheet.CopyTo(workbook, "Sheet1", true, true);
        //    using (MemoryStream ms = new MemoryStream())
        //    {
        //        workbook.Write(ms);
        //        ms.Flush();
        //        ms.Position = 0;
        //        return ms;
        //    }
        //}

    }
}